# frozen_string_literal: true

class UpdateTriggerUpdateVulnerabilityReadsOnVulnerabilityUpdate < Gitlab::Database::Migration[2.0]
  include Gitlab::Database::SchemaHelpers

  TRIGGER_NAME = 'trigger_update_vulnerability_reads_on_vulnerability_update'
  FUNCTION_NAME = 'update_vulnerability_reads_from_vulnerability'

  enable_lock_retries!

  def up
    drop_trigger(:vulnerabilities, TRIGGER_NAME)

    # If the vulnerability record was not already marked as `present_on_default_branch`,
    # we shouldn't try to update `vulnerability_records` since there will be no records
    # anyway.
    execute(<<~SQL)
      CREATE TRIGGER #{TRIGGER_NAME}
      AFTER UPDATE ON vulnerabilities
      FOR EACH ROW
      WHEN (
        OLD.present_on_default_branch IS TRUE AND
        (
          OLD.severity IS DISTINCT FROM NEW.severity OR
          OLD.state IS DISTINCT FROM NEW.state OR
          OLD.resolved_on_default_branch IS DISTINCT FROM NEW.resolved_on_default_branch
        )
      )
      EXECUTE PROCEDURE #{FUNCTION_NAME}();
    SQL
  end

  def down
    drop_trigger(:vulnerabilities, TRIGGER_NAME)

    execute(<<~SQL)
      CREATE TRIGGER #{TRIGGER_NAME}
      AFTER UPDATE ON vulnerabilities
      FOR EACH ROW
      WHEN (
        OLD.severity IS DISTINCT FROM NEW.severity OR
        OLD.state IS DISTINCT FROM NEW.state OR
        OLD.resolved_on_default_branch IS DISTINCT FROM NEW.resolved_on_default_branch
      )
      EXECUTE PROCEDURE #{FUNCTION_NAME}();
    SQL
  end
end
